package com.jlastu.androiduidemo.views;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.jlastu.androiduidemo.R;
import com.jlastu.androiduidemo.database.DBHelper;

//更改密码
public class AlterKeyActivity extends AppCompatActivity {

    private DBHelper dbHelper;
    private EditText oldPasswordEt, newPasswordEt, confirmNewPasswordEt;
    private Button changePasswordButton;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change);

        // 初始化数据库帮助类
        dbHelper = DBHelper.getInstance(this);

        // 初始化SharedPreferences
        sharedPreferences = getSharedPreferences("user_data", MODE_PRIVATE);

        // 绑定控件
        oldPasswordEt = findViewById(R.id.old_password_et);
        newPasswordEt = findViewById(R.id.new_password_et);
        confirmNewPasswordEt = findViewById(R.id.confirm_password_et);
        changePasswordButton = findViewById(R.id.change_password_button);

        // 设置按钮的点击监听器
        changePasswordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changePassword();
            }
        });
    }

    private void changePassword() {
        String oldPassword = oldPasswordEt.getText().toString().trim();
        String newPassword = newPasswordEt.getText().toString().trim();
        String confirmNewPassword = confirmNewPasswordEt.getText().toString().trim();
        String username = sharedPreferences.getString("username", "");

        // 检查输入是否为空
        if (oldPassword.isEmpty() || newPassword.isEmpty() || confirmNewPassword.isEmpty()) {
            Toast.makeText(this, "所有字段都不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查新密码和确认密码是否一致
        if (!newPassword.equals(confirmNewPassword)) {
            Toast.makeText(this, "新密码和确认密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        // 验证旧密码
        if (dbHelper.checkUserName(username, oldPassword)==true) {
            // 旧密码正确，更新新密码
            dbHelper.updateStudentPassWordByUsername(username, newPassword);
            Toast.makeText(this, "密码修改成功", Toast.LENGTH_SHORT).show();
            // 可以在这里添加逻辑，比如返回到登录界面或者主界面
            Intent intent = new Intent(AlterKeyActivity.this,SettingsActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            // 旧密码错误
            Toast.makeText(this, "旧密码不正确", Toast.LENGTH_SHORT).show();
        }
    }
}